package com.wsc.frontier;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.nio.DefaultServerIOEventDispatch;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.entity.NFileEntity;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.nio.protocol.BufferingHttpServiceHandler;
import org.apache.http.nio.protocol.EventListener;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.ListeningIOReactor;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerRegistry;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
 

/**
 *
 * @author N V Reddy
 */
@SuppressWarnings("deprecation")
public class FrontierServer implements Runnable {
    int port;
    String ip,docRoot;
    ListeningIOReactor ioReactor;
    
    
    FrontierServer(){
		this.port = FrontierDetails.getFrontierServerPort();
		this.docRoot = FrontierDetails.getServerRootDirectory();
		
	}
    
    
    @Override
    public void run() {
        try {
            startServer();
        } catch (Exception ex) {
            Logger.getLogger(FrontierServer.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("error in starting server");
        }
    }
    
    public void stopServer() throws IOException{
        ioReactor.shutdown();
    }
    
    public void stopFrontierServer(){
    	Frontier.shutdown = true;
    }
   
    public void startServer() throws Exception {
        //create basic parameters
        HttpParams params = new SyncBasicHttpParams();
        params
            .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
        
        //create basic interceptors to httpprocessor
        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
                new ResponseDate(),
                new ResponseServer(),
                new ResponseContent(),
                new ResponseConnControl()
        });
        
        BufferingHttpServiceHandler handler = new BufferingHttpServiceHandler(
                httpproc,
                new DefaultHttpResponseFactory(),
                new DefaultConnectionReuseStrategy(),
                params);

        // Set up request handlers
        HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
        reqistry.register("*", new HttpFileHandler(docRoot,this));

        handler.setHandlerResolver(reqistry);

        // Provide an event logger
        handler.setEventListener(new EventLogger());

        IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(handler, params);
        ioReactor = new DefaultListeningIOReactor(2, params);
        try {
            ioReactor.listen(new InetSocketAddress(port));
            ioReactor.execute(ioEventDispatch);
        } catch (InterruptedIOException ex) {
            System.err.println("Interrupted");
        } catch (IOException e) {
            System.err.println("I/O error: " + e.getMessage());
        }
        System.out.println("Shutdown");
    }

    static class HttpFileHandler implements HttpRequestHandler  {

        private final String docRoot;
        FSSupport fs_support;
        FrontierServer fs_server;

        public HttpFileHandler(final String docRoot,FrontierServer fronser) {
            super();
            this.docRoot = docRoot;
            fs_support = new FSSupport();
            fs_server = fronser;
        }

        @Override
        public void handle(
                final HttpRequest request,
                final HttpResponse response,
                final HttpContext context) throws HttpException, IOException {
            
            String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
            Header h1= request.getFirstHeader("reqtype");
            String reqtype = h1.getValue();
            
            if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
                throw new MethodNotSupportedException(method + " method not supported");
            }

            

            String target = request.getRequestLine().getUri();
            final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8"));
            if (!file.exists()) {

                response.setStatusCode(HttpStatus.SC_NOT_FOUND);
                NStringEntity entity = new NStringEntity(
                        "<html><body><h1>File" + file.getPath() +
                        " not found</h1></body></html>", "UTF-8");
                entity.setContentType("text/html; charset=UTF-8");
                response.setEntity(entity);
                System.out.println("File " + file.getPath() + " not found");

            } else if (!file.canRead() || file.isDirectory()) {

                response.setStatusCode(HttpStatus.SC_FORBIDDEN);
                NStringEntity entity = new NStringEntity(
                        "<html><body><h1>Access denied</h1></body></html>",
                        "UTF-8");
                entity.setContentType("text/html; charset=UTF-8");
                response.setEntity(entity);
                System.out.println("Cannot read file " + file.getPath());

            } else {
                response.setStatusCode(HttpStatus.SC_OK);
                System.out.println("switch case reqtype:"+reqtype);
                        if(reqtype.equals("heartbeat")) {
                                //handle heartbeat
                                NFileEntity body = new NFileEntity(file, "text/html");
                                response.setEntity(body);
                                System.out.println("Serving file " + file.getPath());
                                System.out.println("heartbeat request processed");

                        }else if(reqtype.equals("takeurls")){
                                if (request instanceof HttpEntityEnclosingRequest) {
                                HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
                                //xml file which stores the urls send by crawlernode
                                Date dt = new Date();
                        		Timer t = new Timer();
                        		DateFormat df = new SimpleDateFormat("yyyy-mm-dd-hh-mm-ss");
                        		String receivedfilename = "path"+"url"+df.format(dt)+".xml";
                                entity.writeTo(new FileOutputStream(receivedfilename));
                                fs_support.takeURLs(receivedfilename);
                                }
                                else{
                                    //handle no entity found
                                }

                        }
                        else if(reqtype.equals("sendurls")){
                                //send urls to the crawler
                                //xml file path which contains the urls to be send to controller
                            	String sendfilename = fs_support.sendURLs();
                            	if(sendfilename.equals(null)){
                            		//no urls found
                            	}
                            	else{
                            		File xmlfile = new File(sendfilename);
                            		FileEntity xml_entity = new FileEntity(xmlfile,ContentType.APPLICATION_ATOM_XML);
                            		response.setEntity(xml_entity);
                            	}

                        }else if(reqtype.equals("shutdown")){
                            	fs_server.stopFrontierServer();
                        }
                

            }
        }

    }

    static class EventLogger implements EventListener {

        @Override
        public void connectionOpen(final NHttpConnection conn) {
            System.out.println("Connection open: " + conn);
        }

        @Override
        public void connectionTimeout(final NHttpConnection conn) {
            System.out.println("Connection timed out: " + conn);
        }

        @Override
        public void connectionClosed(final NHttpConnection conn) {
            System.out.println("Connection closed: " + conn);
        }

        @Override
        public void fatalIOException(final IOException ex, final NHttpConnection conn) {
            System.err.println("I/O error: " + ex.getMessage());
        }

        @Override
        public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) {
            System.err.println("HTTP error: " + ex.getMessage());
        }

    }

    
}
